# -*- coding: utf-8 -*-

import json
import time
import sys
# sys.path.append('.')
import os
# sys.path.append(os.path.abspath(os.path.curdir) + '\\python')
import method
import websocket
from websocket._exceptions import WebSocketConnectionClosedException


def start():
    """监听服务器下发的信息"""
    getattr(method, 'run_log_post')()
    while True:
        try:
            recv = method.ws.recv()
            method.logger.info('接收: ' + recv)
            if not recv:
                continue
            j = json.loads(recv)
            # method.logger.info(f'json化：{json.dumps(j, ensure_ascii=False)}')
            try:
                method_name = j.get('method', None)
                if not method_name:
                    continue
                method.marry(method_name, (j['data']))
            except:
                if j['method'] == 'restart':
                    restart()
                else:
                    raise
        except json.JSONDecodeError:
            method.logger.exception('接收数据解析失败！')
        except Exception as exception:
            s = repr(exception)
            if 'WebSocketConnectionClosedException' in s or 'ConnectionResetError' in s:
                method.try_reconnect()
            raise


def restart():
    method.logger.info("准备重启中...")
    getattr(method, 'restart_ready')()
    python = sys.executable
    os.execl(python, python, * sys.argv)


def main():
    method.set_slave_log()
    method.register()
    start()


if __name__ == '__main__':
    main()

